<?php

namespace falcon5\inc\WPProviders;

use falcon5\inc\Base\ServiceProviderInterface;
use falcon5\inc\Http\Request;

/**
 * Class Route
 * @package falcon5\inc\WPProviders
 * @desc Ajax route config using WordPress admin-ajax.php
 */
class Route implements ServiceProviderInterface
{
    /**
     * 控制器实例缓存
     */
    private $controllerInstances = [];

    /**
     * 路由配置
     */
    private $routes;

    /**
     * 构造函数，加载路由配置
     */
    public function __construct()
    {

        $this->routes = require_once plugin_dir_path(dirname(__FILE__, 2)) . 'config/routes.php';
    }

    /**
     * 获取控制器实例
     */
    private function getController(string $controllerClass)
    {
        if (!isset($this->controllerInstances[$controllerClass])) {
            if (!class_exists($controllerClass)) {
                throw new \Exception("Controller class {$controllerClass} not found");
            }
            $this->controllerInstances[$controllerClass] = new $controllerClass();
        }
        return $this->controllerInstances[$controllerClass];
    }

    /**
     * 处理 AJAX 请求
     */
    private function handleAjaxRequest($prefix, $action)
    {
        try {
            if (!isset($this->routes[$prefix])) {
                throw new \Exception("Route prefix '{$prefix}' not found");
            }

            $group = $this->routes[$prefix];
            if (!isset($group['routes'][$action])) {
                throw new \Exception("Action '{$action}' not found in '{$prefix}' group");
            }

            $config = $group['routes'][$action];
            $request = new Request();
            $controller = $this->getController($group['controller']);
            
            // 设置当前的动作名，这样控制器可以知道要调用哪个方法
            $request->setAction($config['method']);
            
            return $controller->handleRequest($request);
        } catch (\Exception $e) {
            falcon5_error_log('AJAX request error: ' . $e->getMessage());
            throw $e;
        }
    }

    /**
     * 注册单个路由
     */
    private function registerRoute(string $prefix, string $action, array $config, string $controllerClass)
    {
        $fullAction = $prefix ? "{$prefix}_{$action}" : $action;
        
        // 注册登录用户可访问的路由
        add_action("wp_ajax_{$fullAction}", function() use ($prefix, $action) {
            try {
                // 处理请求并获取响应
                $response = $this->handleAjaxRequest($prefix, $action);
                
                // 确保所有输出缓冲区被清空
                while (ob_get_level()) {
                    ob_end_clean();
                }
                
                // 发送响应
                $response->send();
                exit; // 确保没有其他代码执行
            } catch (\Exception $e) {
                // 错误日志
                falcon5_error_log('AJAX error: ' . $e->getMessage());
                
                // 确保所有输出缓冲区被清空
                while (ob_get_level()) {
                    ob_end_clean();
                }
                
                // 手动设置HTTP状态码
                status_header(500);
                
                // 发送错误响应
                wp_send_json_error([
                    'message' => $e->getMessage(),
                    'code' => $e->getCode() ?: 500
                ]);
                exit;
            }
        });

        // 如果允许公开访问，注册未登录用户可访问的路由
        if ($config['public'] ?? false) {
            add_action("wp_ajax_nopriv_{$fullAction}", function() use ($prefix, $action) {
                try {
                    // 处理请求并获取响应
                    $response = $this->handleAjaxRequest($prefix, $action);
                    
                    // 确保所有输出缓冲区被清空
                    while (ob_get_level()) {
                        ob_end_clean();
                    }
                    
                    // 发送响应
                    $response->send();
                    exit; // 确保没有其他代码执行
                } catch (\Exception $e) {
                    // 错误日志
                    falcon5_error_log('AJAX error: ' . $e->getMessage());
                    
                    // 确保所有输出缓冲区被清空
                    while (ob_get_level()) {
                        ob_end_clean();
                    }
                    
                    // 手动设置HTTP状态码
                    status_header(500);
                    
                    // 发送错误响应
                    wp_send_json_error([
                        'message' => $e->getMessage(),
                        'code' => $e->getCode() ?: 500
                    ]);
                    exit;
                }
            });
        }
    }

    /**
     * 注册路由组
     */
    private function registerGroup(string $prefix, array $group)
    {
        $controllerClass = $group['controller'];
        foreach ($group['routes'] as $action => $config) {
            $this->registerRoute($prefix, $action, $config, $controllerClass);
        }
    }

    public function register()
    {
        // 注册所有路由组
        foreach ($this->routes as $prefix => $group) {
            $this->registerGroup($prefix, $group);
        }
    }
}